<?php

// +----------------------------------------------------------------------
// | yogurt
// +----------------------------------------------------------------------
// +----------------------------------------------------------------------
// | Author: fengyi <1719847255.qq.com>
// +----------------------------------------------------------------------

namespace yogurt;

use yogurt\file\File;

class Log
{

    /**
     * 获取日志文件
     * @param $date
     * @param string $type
     * @return string
     */
    public static function getLogFile($date, $type = 'access'): string
    {
        $logPath = RUNTIME_PATH . 'log' . DIRECTORY_SEPARATOR . $date . DIRECTORY_SEPARATOR;
        if (!is_dir($logPath)) {
            File::directory($logPath);
        }
        return $logPath . md5($type) . '.log';
    }

    /**
     * 日志写入
     * @param $data
     * @param string $type
     * @return false|int
     */
    public static function write($data, $type = 'access')
    {
        $logFile = self::getLogFile(date('Y-m-d'), $type);
        $jsonData['create_at'] = date('Y-m-d H:i:s');
        $jsonData['data'] = json_encode($data, JSON_UNESCAPED_UNICODE);
        return file_put_contents($logFile, json_encode($jsonData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
    }

    /**
     * 获取日志
     * @param $date
     * @param string $type
     * @return false|string[]
     */
    public static function get($date, $type = 'access')
    {
        $logFile = self::getLogFile($date, $type);
        $logStr = file_get_contents($logFile);
        $logArr = explode(PHP_EOL, $logStr);
        foreach ($logArr as $key => &$value) {
            if (!empty($value)) {
                $value = json_decode($value, true);
                $value['data'] = json_decode(json_decode($value['data'], true), true);
            } else {
                unset($logArr[$key]);
            }
        }
        sort($logArr);
        return $logArr;
    }
}